package com.carreirati.security;

import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.carreirati.evaluation.domain.UserLogin;

import java.util.HashMap;
import java.util.Map;

public class UserDetailsServiceImpl implements UserDetailsService {


    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {

        UserLogin ul = findUserFromDatabase(userId);

        return new User(ul.getUserId(), ul.getPassword(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(ul.getAuthorities()));
    }

    private UserLogin findUserFromDatabase(String userId) {  
    	UserLogin ul = UserLogin.findUserLoginByEmail(userId);
    	
    	if(ul == null)
    		ul = UserLogin.findUserLogin(userId);
    	
    	return ul;
    }
}
